package cn.org.timespace.easyframe.dao.permission.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;

import cn.org.timespace.easyframe.dao.EfBaseDAO;
import cn.org.timespace.easyframe.dao.permission.EfUserRoleDao;
import cn.org.timespace.easyframe.model.permission.EfUserRole;

public class EfUserRoleDaoImpl extends EfBaseDAO implements EfUserRoleDao {

	public List<EfUserRole> findByCondition(String roleId) {
		
		StringBuffer queryString = new StringBuffer("from EfUserRole a where 1=1");

		if (!StringUtils.isEmpty(roleId)) {
			queryString.append(" and a.efRole.roleId = '"+roleId+"'");
		}

		return getHibernateTemplate().find(queryString.toString());
	} 

	public void save(EfUserRole transientInstance) {
		log.debug("saving EfUserRole instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(EfUserRole persistentInstance) {
		log.debug("deleting EfUserRole instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public void delete(String roleId) {
		log.debug("deleting EfUserRole by roleId");
		try {
			StringBuffer deleteSql = new StringBuffer("delete from EfUserRole a where a.efRole.roleId ='"+roleId+"' ");
			Query q = getSession().createQuery(deleteSql.toString());
			int i = q.executeUpdate();
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	/**
	 * 根据用户ID，找出他所有的用户角色表
	 * */
	
	public List<EfUserRole> findUserRoleByUserId(String userId) {
		StringBuffer queryString = new StringBuffer("from EfUserRole a where 1=1 ");

		if (!StringUtils.isEmpty(userId)) {
			queryString.append(" and a.efUser.userId= '" + userId + "'");
		}

		return getHibernateTemplate().find(queryString.toString());
	}
	
}
